package com.example.mqttledmenu;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Download {

    private String fileSavePath = "";//保存文件的本地路径
    private String fileDownLoad_path = "";//下载的URL
    private String fileName = "";//下载的文件名字
    private boolean mIsCancel = false;
    private int mProgress;
    private ProgressBar mProgressBar;
    private TextView text;
    private Dialog mDownloadDialog;
    private final Context context;

    private static final int DOWNLOADING = 1;
    private static final int DOWNLOAD_FINISH = 2;

    @SuppressLint("HandlerLeak")
    private final Handler mUpdateProgressHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOADING:
                    // 设置进度条
                    mProgressBar.setProgress(mProgress);
                    text.setText(String.valueOf(mProgress));
                    break;
                case DOWNLOAD_FINISH:
                    // 隐藏当前下载对话框
                    mDownloadDialog.dismiss();
            }
        }
    };

    /**
     * 下载初始化
     *
     * @param context           上下文
     * @param fileDownLoad_path 下载的URL
     * @param fileName          下载的文件名字
     * @param fileSavePath      保存文件的本地路径
     */
    public Download(Context context, String fileDownLoad_path, String fileSavePath, String fileName) {
        this.context = context;
        this.fileDownLoad_path = fileDownLoad_path;
        this.fileName = fileName;
        this.fileSavePath = Environment.getExternalStorageDirectory() + "/" + fileSavePath;
        showDownloadDialog();
    }

    /**
     * 显示正在下载的对话框
     */
    protected void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("下载中");
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_progress, null);
        mProgressBar = (ProgressBar) view.findViewById(R.id.id_progress);
        text = view.findViewById(R.id.id_text);
        builder.setView(view);

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 隐藏当前对话框
                dialog.dismiss();
                // 设置下载状态为取消
                mIsCancel = true;
            }
        });

        mDownloadDialog = builder.create();
        mDownloadDialog.show();
        downloadFile();
    }

    public static ContentValues getImageContentValues(Context paramContext, File paramFile, long paramLong) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("title", paramFile.getName());
        localContentValues.put("_display_name", paramFile.getName());
        localContentValues.put("mime_type", "image/jpeg");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        localContentValues.put("orientation", Integer.valueOf(0));
        localContentValues.put("_data", paramFile.getAbsolutePath());
        localContentValues.put("_size", Long.valueOf(paramFile.length()));
        return localContentValues;
    }

    /**
     * 下载文件
     */
    private void downloadFile() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        File dir = new File(fileSavePath);
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        HttpURLConnection conn = (HttpURLConnection) new URL(fileDownLoad_path).openConnection();
                        conn.connect();
                        InputStream is = conn.getInputStream();
                        int length = conn.getContentLength();

                        File imageFile = new File(fileSavePath, fileName);
                        FileOutputStream fos = new FileOutputStream(imageFile);

                        int count = 0;
                        byte[] buffer = new byte[1024];
                        while (!mIsCancel) {
                            int numread = is.read(buffer);
                            count += numread;
                            // 计算进度条当前位置
                            mProgress = (int) (((float) count / length) * 100);
                            // 更新进度条
                            mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING);

                            // 下载完成
                            if (numread < 0) {
                                mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                                break;
                            }
                            fos.write(buffer, 0, numread);
                        }

                        //将文件写入相册
                        ContentResolver localContentResolver = context.getContentResolver();
                        ContentValues localContentValues = getImageContentValues(context, imageFile, System.currentTimeMillis());
                        localContentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, localContentValues);

                        Intent localIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
                        final Uri localUri = Uri.fromFile(imageFile);
                        localIntent.setData(localUri);
                        context.sendBroadcast(localIntent);

                        Log.d("nightowl:", "run: " + "文件下载完成," + fileSavePath + fileName);
                        fos.close();
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}